package com.itouch.bracelet.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.fourmob.datetimepicker.date.DatePickerDialog;
import com.fourmob.datetimepicker.date.DatePickerDialog.OnDateSetListener;
import com.google.gson.Gson;
import com.itouch.bracelet.R;
import com.itouch.bracelet.bean.Child;
import com.itouch.bracelet.bean.ChildRegisterResult;
import com.itouch.bracelet.bean.LoginUser;
import com.itouch.bracelet.bluetooth.BluetoothConstants;
import com.itouch.bracelet.bluetooth.BluetoothPacket;
import com.itouch.bracelet.bluetooth.BluetoothSpp;
import com.itouch.bracelet.bluetooth.BluetoothUtil;
import com.itouch.bracelet.bluetooth.BluetoothValue;
import com.itouch.bracelet.cache.UserCache;
import com.itouch.bracelet.diseaseinfo.Constants;
import com.itouch.util.JsonAndPhpUtil;

public class ChildRegisterActivity extends BaseActivity implements
		OnClickListener, OnDateSetListener {
	public static final String DATEPICKER_TAG = "datepicker";
	private EditText childName;
	private EditText childDate;
	private EditText deviceCode;
	private TextView deviceCodeGet;
	private TextView commit_register;
	private RadioGroup sex;
	private RadioButton male;
	private RadioButton female;
	private static final int requestQRCode = 0x2234;
	private ImageView calendarView;
	private DatePickerDialog startDatePickerDialog;

	@Override
	protected int setContentViewById() {
		return R.layout.activity_child_register;
	}

	@Override
	protected void initViews() {
		final Calendar calendar = Calendar.getInstance();
		startDatePickerDialog = DatePickerDialog.newInstance(this,
				calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH), false);

		childName = (EditText) findViewById(R.id.child_name);
		childDate = (EditText) findViewById(R.id.child_date);
		deviceCode = (EditText) findViewById(R.id.device_code);
		deviceCodeGet = (TextView) findViewById(R.id.device_code_get);
		commit_register = (TextView) findViewById(R.id.commit_register);
		calendarView = (ImageView) findViewById(R.id.calendar);

		deviceCodeGet.setOnClickListener(this);
		calendarView.setOnClickListener(this);
		commit_register.setOnClickListener(this);
		sex = (RadioGroup) findViewById(R.id.sex);
		male = (RadioButton) findViewById(R.id.male);
		female = (RadioButton) findViewById(R.id.female);

	}

	@Override
	protected void initData() {

	}

	@Override
	public void onClick(View v) {
		Intent it = null;
		switch (v.getId()) {
		case R.id.calendar:
			startDatePickerDialog.setVibrate(true);
			startDatePickerDialog.setYearRange(1985, 2028);
			startDatePickerDialog.setCloseOnSingleTapDay(true);
			startDatePickerDialog.show(getSupportFragmentManager(),
					DATEPICKER_TAG);

			break;
		case R.id.device_code_get:
			// 获取设备号
			it = new Intent(context, QrCodeActivity.class);
			startActivityForResult(it, requestQRCode);

			break;
		case R.id.commit_register:
			String nameString = childName.getText().toString();
			if (nameString == null || nameString.length() < 1) {
				Toast.makeText(context, R.string.register_child_name,
						Toast.LENGTH_LONG).show();
				return;
			}

			if (!male.isChecked() && !female.isChecked()) {
				Toast.makeText(context, R.string.register_child_sex,
						Toast.LENGTH_LONG).show();
				return;
			}

			String dateString = childDate.getText().toString();
			if (dateString == null || dateString.length() < 1) {
				Toast.makeText(context, R.string.register_child_date,
						Toast.LENGTH_LONG).show();
				return;
			}

			String deviceString = deviceCode.getText().toString();
			/*if (deviceString == null || deviceString.length() < 8) {
				Toast.makeText(context, R.string.register_device,
						Toast.LENGTH_LONG).show();
				return;
			}*/
			String sex = male.isChecked() ? "1" : "0"; // 1:男， 2：女
//			childRegister(dateString, deviceString, nameString, sex);
			
			if(!deviceString.equals("")){
				
				if (BluetoothUtil.getDeviceType(deviceString)==0) {
					Toast.makeText(context, R.string.register_device,
							Toast.LENGTH_LONG).show();
					return;
				}
				
				if(BluetoothValue.INSTANCE.getConnectStatus()!=BluetoothConstants.STATUS_CONNECTED){
					Toast.makeText(this, "连接手环后才能设置设备号！", Toast.LENGTH_SHORT)
					.show();
					return;
				}
			
			}
			
			new ChildRegisterAsync(dateString, deviceString, nameString, sex).execute();

			break;

		default:
			break;

		}

	}

	// http://192.168.3.46:81/handchain/mobi/registration/childrenlist?1=1&bornTime=2015-01-09&childDeviceNum
	// =dnilwedh2pew&deviceType=2&name=coco&parentId=86&sex=2
	private void childRegister(String bornTime, String childDeviceNum,
			String name, String sex) {

		RequestQueue requestQueue = Volley.newRequestQueue(this);
		
		Uri.Builder builder = Uri.parse(Constants.CHILD_REGISTER).buildUpon();

		LoginUser user = UserCache.getOauth(context);
		if (user == null) {
			return;
		}

		builder.appendQueryParameter("bornTime", bornTime);
		builder.appendQueryParameter("childDeviceNum", childDeviceNum + "");
		builder.appendQueryParameter("sex", sex + "");
		builder.appendQueryParameter("name", name + "");
		builder.appendQueryParameter("deviceType", 2 + "");
		builder.appendQueryParameter("parentId", user.getUserId());

		Log.d("CHILD_REGISTER", "CHILD_REGISTER" + builder.toString());

		show();
		
		JsonObjectRequest joq = new JsonObjectRequest(
				Request.Method.GET, 
		builder.toString(),null,
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject arg0) {
						disMiss();
						Log.d("CHILD_REGISTER",
								"CHILD_REGISTER" + arg0.toString());
						try {
							ChildRegisterResult a = new Gson().fromJson(
									arg0.toString(), ChildRegisterResult.class);
							if (a == null) {
								return;
							}
							if (a.isFlag()) {
								Toast.makeText(context, R.string.child_register_ok,
										Toast.LENGTH_LONG).show();
								//注册成功后将小孩的信息缓存	
								LoginUser user = UserCache.getOauth(context);
								ArrayList<Child> list = user.getChildlist();
								if (list == null) {
									list = new ArrayList<Child>();
								}
								list.add(a.getRows());
								UserCache.saveOAuth(user, context);
								ChildRegisterActivity.this.finish();
							} else {
								Toast.makeText(context, a.getMsg() + "",
										Toast.LENGTH_LONG).show();
							}
						} catch (Exception e) {
						}
					}

				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						disMiss();
						Toast.makeText(context,
								getString(R.string.net_error) + "",
								Toast.LENGTH_LONG).show();
					}
				});
		requestQueue.add(joq);
	}
	
	
	/**
	 * 
	 * 小孩注册的AsyncTask
	 */
	class ChildRegisterAsync extends AsyncTask<String, String, String> {

		String bornTime; String childDeviceNum;
		String name;String sex;

		public ChildRegisterAsync(String bornTime, String childDeviceNum,
				String name, String sex) {
			super();
			this.bornTime = bornTime;
			this.childDeviceNum = childDeviceNum;
			this.name = name;
			this.sex = sex;
		}

		

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			show();
		}

		@Override
		protected String doInBackground(String... params) {
			String ss = null;
			try {
				Uri.Builder builder = Uri.parse(Constants.CHILD_REGISTER).buildUpon();
				List<NameValuePair> lists = new ArrayList<NameValuePair>();
				LoginUser user = UserCache.getOauth(context);
				
				lists.add(new BasicNameValuePair("bornTime", bornTime));
				lists.add(new BasicNameValuePair("childDeviceNum", childDeviceNum + ""));
				lists.add(new BasicNameValuePair("sex", sex + ""));
				lists.add(new BasicNameValuePair("name", name + ""));
				lists.add(new BasicNameValuePair("deviceType", 2 + ""));
				lists.add(new BasicNameValuePair("parentId", user.getUserId()));

				Log.d("CHILD_REGISTER", "CHILD_REGISTER" + builder.toString());
				
				ss = JsonAndPhpUtil.postHttpData(Constants.CHILD_REGISTER, lists, context);
			} catch (Exception e) {

			}
			return ss;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			disMiss();
			if (result == null || "".equals(result)) {
				return;
			}
			Log.d("CHILD_REGISTER",
					"CHILD_REGISTER" + result.toString());
			try {
				ChildRegisterResult a = new Gson().fromJson(
						result.toString(), ChildRegisterResult.class);
				if (a == null) {
					return;
				}
				if (a.isFlag()) {
					Toast.makeText(context, R.string.child_register_ok,
							Toast.LENGTH_LONG).show();
					//注册成功后将小孩的信息缓存	
					LoginUser user = UserCache.getOauth(context);
					ArrayList<Child> list = user.getChildlist();
					if (list == null) {
						list = new ArrayList<Child>();
					}
					list.add(a.getRows());
					UserCache.saveOAuth(user, context);
					
					sendPacket();
					
					ChildRegisterActivity.this.finish();
				} else {
					Toast.makeText(context, a.getMsg() + "",
							Toast.LENGTH_LONG).show();
				}
			} catch (Exception e) {
			}

		}
	}
	
	

	@Override
	public void onDateSet(DatePickerDialog datePickerDialog, int year,
			int month, int day) {
		if (year == 0) {
			childDate.setText("");
			return;
		}
		Date d = new Date();
		d.setYear(year - 1900);
		d.setMonth(month);
		d.setDate(day);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String date = sdf.format(d);
		childDate.setText(date);

	}

	
	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, intent);
		
		if(requestCode==requestQRCode){
			
			deviceCode.setText(intent.getStringExtra("code"));
			
		}
	}
	
	
	

	//发送设备号给设备
	private void sendPacket(){
		
		if(BluetoothValue.INSTANCE.getConnectStatus()==BluetoothConstants.STATUS_CONNECTED){
			
			BluetoothPacket packet=new BluetoothPacket();
			int type=1;//mother
			
			String deviceString = deviceCode.getText().toString();
			int deviceType=BluetoothUtil.getDeviceType(deviceString);//当前注册的类型
			
			List<Byte> lists=new ArrayList<Byte>();
			for(Child child:UserCache.getOauth(this).getChildlist()){
				String deviceNo=child.getDeviceNo();
				if(BluetoothUtil.getDeviceType(deviceNo)==deviceType){
					String[] parts=deviceNo.split(":");
					if(parts.length==2){
						int part1=Integer.valueOf(parts[0]);
						int part2=Integer.valueOf(parts[1]);
						lists.add((byte)part1);
						lists.add((byte)part2);
					}
				}
			}
			
			if(lists.size()>0){
				int lenth=lists.size()/2;
				int size=lists.size()+4;
				byte[] con=new byte[size];
				
				//根据设备类型设置是绑定儿童还是婴儿
				if(deviceType==1){
					con[0]=(byte) 0xE7;
				}else if(deviceType==2){
					con[0]=(byte) 0xE6;
				}
				
				con[1]=(byte) lenth;
				con[2]=(byte) 0;
				con[3]=(byte) 0x0A;
				for(int i=4;i<size;i++){
					con[i]=lists.get(i-4);
				}
				packet.setData(con);
				
				if (BluetoothValue.INSTANCE.id != null) {
					packet.setId(BluetoothValue.INSTANCE.id);
				} else {
					return;
				}
				BluetoothUtil.packetData(packet, type);
				BluetoothSpp.getInstance().sendPacket(packet);
			}else{
				return;
			}
			
			
		}
		
	}
	
	
	
}
